package logic

import (
	"backend/apps/book/models"
	"context"
	"github.com/pkg/errors"

	"backend/apps/book/proto"
	"backend/apps/book/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetBookLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetBookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBookLogic {
	return &GetBookLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetBookLogic) GetBook(in *proto.IdRequest) (*proto.Book, error) {
	book, err := l.svcCtx.BookModel.FindOne(l.ctx, in.Id)
	if err != nil {
		if errors.Is(err, models.ErrNotFound) {
			return nil, errors.New("作者信息不存在")
		}
		return nil, err
	}

	return &proto.Book{
		Id:         book.Id,
		AuthorId:   book.AuthorId,
		Title:      book.Title,
		CoverUrl:   book.CoverUrl,
		Summary:    book.Summary.String,
		TotalWords: book.TotalWords,
		IsVip:      int32(book.IsVip),
		Status:     int32(book.Status),
	}, nil
}
